package com.czkevin.cif.crafting.gui;

import com.czkevin.cif.CustomItemFramework;
import com.czkevin.cif.utils.ParameterCallback;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.HumanEntity;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack;
import com.czkevin.guicontrolsapi.ItemUtils;
import com.czkevin.guicontrolsapi.controls.GUIControl;

public class CraftingOutputControl extends GUIControl {

    public static final ItemStack ITEMSTACK_NO_OUTPUT = ItemUtils.putMeta(new ItemStack(Material.BARRIER), "\u00a7c\u00a7lNo Output");

    private ItemStack output = null;
    private ParameterCallback<HumanEntity, Boolean> callback = null;

    public CraftingOutputControl() {
    }

    public CraftingOutputControl(ParameterCallback<HumanEntity, Boolean> callback) {
        this.callback = callback;
    }

    public void setOutput(ItemStack output) {
        this.output = output;
        onRender(true);
    }

    public ItemStack getOutput() {
        return output;
    }

    public void setCallback(ParameterCallback<HumanEntity, Boolean> callback) {
        this.callback = callback;
    }

    @Override
    public void onClick(InventoryClickEvent inventoryClickEvent, int i, int i1) {
        /*
        System.out.println("====================");
        System.out.println("=== output: " + (output == null?"NULL":output.getType().name()));
        System.out.println("=== is shift: " + (inventoryClickEvent.isShiftClick()?"YES":"NO"));
        System.out.println("=== click: " + inventoryClickEvent.getAction().name());
        System.out.println("=== cursor: " + (inventoryClickEvent.getCursor() == null ? "NULL":inventoryClickEvent.getCursor().getType().name()));
        System.out.println("=== callback: " + (callback == null ? "NULL" : "ok"));
        System.out.println("====================");
        */
        if(output == null) return;
        if(!inventoryClickEvent.getAction().name().startsWith("PICKUP_") || inventoryClickEvent.isShiftClick()) return;
        ItemStack cursor = inventoryClickEvent.getCursor();
        if(cursor != null && cursor.getType() != Material.AIR) return;
        if(callback == null) return;
        Boolean good = callback.call(inventoryClickEvent.getWhoClicked());
        if(good == null || !good) return;
        final ItemStack cloned = output.clone();
        output = null;
        onRender(true);
        Bukkit.getScheduler().runTaskLater(CustomItemFramework.getInstance(), () -> {
            inventoryClickEvent.getWhoClicked().setItemOnCursor(cloned);
        }, 1L);
    }

    @Override
    public int getWidth() {
        return 1;
    }

    @Override
    public int getHeight() {
        return 1;
    }

    @Override
    public void onRender(boolean b) {
        getWindow().setDisplayItemAt(getX(), getY(), output != null ? output : ITEMSTACK_NO_OUTPUT);
    }
}
